using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SumerCoreDevOps.Infrastructure.Artifacts;
using SumerCoreDevOps.Infrastructure.Configuration;

namespace SumerCoreDevOps.Infrastructure.HostedServices;

/// <summary>
/// 构建产物定期清理后台服务
/// </summary>
public class ArtifactCleanupHostedService : BackgroundService
{
    private readonly ILogger<ArtifactCleanupHostedService> _logger;
    private readonly BuildArtifactManager _artifactManager;
    private readonly SystemConfigManager _configManager;

    public ArtifactCleanupHostedService(
        ILogger<ArtifactCleanupHostedService> logger,
        BuildArtifactManager artifactManager,
        SystemConfigManager configManager)
    {
        _logger = logger;
        _artifactManager = artifactManager;
        _configManager = configManager;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("构建产物清理服务已启动");

        // 等待系统完全启动后再开始清理
        await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                // 从配置中读取清理间隔（小时）
                var intervalHoursStr = await _configManager.GetConfigValueAsync("Artifact.CleanupIntervalHours");
                if (!int.TryParse(intervalHoursStr, out var intervalHours) || intervalHours <= 0)
                {
                    intervalHours = 24; // 默认 24 小时
                }

                _logger.LogInformation("开始清理过期构建产物...");
                var cleanedCount = await _artifactManager.CleanupExpiredArtifactsAsync();

                if (cleanedCount > 0)
                {
                    _logger.LogInformation("已清理 {Count} 个过期构建产物", cleanedCount);
                }
                else
                {
                    _logger.LogDebug("没有需要清理的过期产物");
                }

                // 等待下次清理
                _logger.LogInformation("下次清理将在 {Hours} 小时后进行", intervalHours);
                await Task.Delay(TimeSpan.FromHours(intervalHours), stoppingToken);
            }
            catch (OperationCanceledException)
            {
                // 正常停止
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理过期产物时发生错误");
                // 出错后等待 1 小时再重试
                await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
            }
        }

        _logger.LogInformation("构建产物清理服务已停止");
    }
}
